/**
 * Copyright (C) 2005-2010 Alfresco Software Limited.
 *
 * This file is part of Alfresco
 *
 * Alfresco is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Alfresco is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Dashboard MyWorkflows component.
 *
 * @namespace Alfresco.dashlet
 * @class Alfresco.dashlet.MyWorkflows
 */
(function()
{
    /**
     * YUI Library aliases
     */
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event,
        Selector = YAHOO.util.Selector;

    /**
     * Alfresco Slingshot aliases
     */
    var $html = Alfresco.util.encodeHTML,
        $siteURL = Alfresco.util.siteURL;

    /**
     * Dashboard MyWorkflows constructor.
     *
     * @param {String} htmlId The HTML id of the parent element
     * @return {Alfresco.dashlet.MyWorkflows} The new component instance
     * @constructor
     */
    Alfresco.dashlet.MyWorkflows = function MyWorkflows_constructor(htmlId)
    {
        Alfresco.dashlet.MyWorkflows.superclass.constructor.call(this, "Alfresco.dashlet.MyWorkflows", htmlId, ["button", "container", "datasource", "datatable", "paginator", "history", "animation"]);

        // Services
        //this.services.preferences = new Alfresco.service.Preferences();

        return this;
    };

    /**
     * Extend from Alfresco.component.Base
     */
    YAHOO.extend(Alfresco.dashlet.MyWorkflows, Alfresco.component.Base);

    /**
     * Augment prototype with Common Workflow actions to reuse createFilterURLParameters
     */
    YAHOO.lang.augmentProto(Alfresco.dashlet.MyWorkflows, Alfresco.action.WorkflowActions);

    /**
     * Augment prototype with main class implementation, ensuring overwrite is enabled
     */
    YAHOO.lang.augmentObject(Alfresco.dashlet.MyWorkflows.prototype,
        {
            /**
             * Preferences
             */
            //PREFERENCES_WORKFLOWS_DASHLET: "",
            //PREFERENCES_WORKFLOWS_DASHLET_FILTER: "",
            /**
             * Object container for initialization options
             *
             * @property options
             * @type object
             */
            options:
            {
                /**
                 * Workflows types not to display
                 *
                 * @property hiddenWorkflowNames
                 * @type object
                 * @default []
                 */
                hiddenWorkflowNames: [],

                /**
                 * Maximum number of workflows to display in the dashlet.
                 *
                 * @property maxItems
                 * @type int
                 * @default 25
                 */
                maxItems: 25
            },

            /**
             * Fired by YUI when parent element is available for scripting
             * @method onReady
             */
            onReady: function MyWorkflows_onReady()
            {
                // Create filter menu
               /*
                this.widgets.filterMenuButton = Alfresco.util.createYUIButton(this, "filters", this.onFilterSelected,
                    {
                        type: "menu",
                        menu: "filters-menu",
                        lazyloadmenu: false
                    });
                */

                // Load preferences (after which the appropriate workflows will be displayed)
                /*
                this.PREFERENCES_WORKFLOWS_DASHLET = this.services.preferences.getDashletId(this, "workflows");
                this.PREFERENCES_WORKFLOWS_DASHLET_FILTER = this.PREFERENCES_WORKFLOWS_DASHLET + ".filter";
                var prefs = this.services.preferences.get();
                */

                // Select the preferred filter in the ui
                /*
                var filter = Alfresco.util.findValueByDotNotation(prefs, this.PREFERENCES_WORKFLOWS_DASHLET_FILTER, "activeWorkflows");
                filter = this.options.filters.hasOwnProperty(filter) ? filter : "activeWorkflows";
                this.widgets.filterMenuButton.set("label", this.msg("filter." + filter));
                this.widgets.filterMenuButton.value = filter;
                */

                // Display the toolbar now that we have selected the filter
                Dom.removeClass(Selector.query(".toolbar div", this.id, true), "hidden");

                // Prepare webscript url to workflow instances
                var webscript = Alfresco.constants.PROXY_URI + "api/workflow-instances-mod?initiator=" + encodeURIComponent(Alfresco.constants.USERNAME) +
                    "&exclude=" + this.options.hiddenWorkflowNames.join(",");

                /**
                 * Create datatable with a simple pagination that only displays number of results.
                 * The pagination is handled in the "base" data source url and can't be changed in the dashlet
                 */
                this.widgets.alfrescoDataTable = new Alfresco.util.DataTable(
                    {
                        dataSource:
                        {
                            url: webscript
                            /*filterResolver: this.bind(function()
                            {
                                // Reuse method form WorkflowActions
                                var filter = this.widgets.filterMenuButton.value;
                                var filterParameters = this.options.filters[filter];
                                return this.substituteParameters(filterParameters) || "";
                            }) */
                        },
                        dataTable:
                        {
                            container: this.id + "-workflows",
                            columnDefinitions:
                                [
                                    { key: "id", sortable: false, formatter: this.bind(this.renderCellIcons), width: 24 },
                                    { key: "title", sortable: false, formatter: this.bind(this.renderCellWorkflowInfo) }
                                    //{ key: "name", sortable: false, formatter: this.bind(this.renderCellActions), width: 150}
                                ],
                            config:
                            {
                                MSG_EMPTY: this.msg("message.noWorkflows")
                            }
                        },
                        paginator:
                        {
                            history: false,
                            hide: false,
                            config:
                            {
                                containers: [this.id + "-paginatorWf"],
                                template: "{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}",
                                firstPageLinkLabel: "&lt;&lt;",
                                previousPageLinkLabel: "&lt;",
                                nextPageLinkLabel: "&gt;",
                                lastPageLinkLabel: "&gt;&gt;",
                                pageReportTemplate: this.msg("pagination.template.page-report"),
                                rowsPerPage: (this.options.maxItems / 5)
                            }
                        }
                    });
            },

            /**
             * Reloads the list with the new filter and updates the filter menu button's label
             *
             * @param p_sType {string} The event
             * @param p_aArgs {array} Event arguments
             */
            /*onFilterSelected: function MyWorkflows_onFilterSelected(p_sType, p_aArgs)
            {
                var menuItem = p_aArgs[1];

                if (menuItem)
                {
                    // Set the currentSkipCount to 0 so after changing the filter the paging starts from the first page
                    // Otherwise an error can occur if the previous taks page has more pages than the new page
                    this.widgets.alfrescoDataTable.currentSkipCount = 0;

                    this.widgets.filterMenuButton.set("label", menuItem.cfg.getProperty("text"));
                    this.widgets.filterMenuButton.value = menuItem.value;

                    var parameters = this.substituteParameters(this.options.filters[menuItem.value], {});
                    this.widgets.alfrescoDataTable.loadDataTable(parameters);

                    // Save preferences
                    this.services.preferences.set(this.PREFERENCES_WORKFLOWS_DASHLET_FILTER, menuItem.value);
                }
            }, */

            /**
             * DataTable Cell Renderers
             */

            /**
             * Priority & pooled icons custom datacell formatter
             *
             * @method renderCellIcons
             * @param elCell {object}
             * @param oRecord {object}
             * @param oColumn {object}
             * @param oData {object|string}
             */
            renderCellIcons: function MyWorkflows_onReady_renderCellIcons(elCell, oRecord, oColumn, oData)
            {
                var priority = oRecord.getData("priority"),
                    priorityMap = { "1": "high", "2": "medium", "3": "low" },
                    priorityKey = priorityMap[priority + ""],
                    desc = '<img src="' + Alfresco.constants.URL_RESCONTEXT + 'components/images/priority-' + priorityKey + '-16.png" title="' + this.msg("label.priority", this.msg("priority." + priorityKey)) + '"/>';
                elCell.innerHTML = desc;
            },

            /**
             * Workflow info custom datacell formatter
             *
             * @method renderCellWorkflowInfo
             * @param elCell {object}
             * @param oRecord {object}
             * @param oColumn {object}
             * @param oData {object|string}
             */
            renderCellWorkflowInfo: function MyWorkflows_onReady_renderCellWorkflowInfo(elCell, oRecord, oColumn, oData)
            {
                var workflow = oRecord.getData();
                var dueDate = workflow.dueDate ? Alfresco.util.fromISO8601(workflow.dueDate) : null,
                    startedDate = workflow.startDate ? Alfresco.util.fromISO8601(workflow.startDate) : null;
                var info = '<h3><a href="' + $siteURL('workflow-details?workflowId=' + workflow.id + '&referrer=workflows&myWorkflowsLinkBack=true') + '" class="theme-color-1" title="' + this.msg("link.viewWorkflow") + '">' + $html(workflow.title) + '</a></h3>';
                info += '<table><tr><td width="30%"><div class="due"><label>' + this.msg("label.due") + ':</label><span>' + (dueDate ? Alfresco.util.formatDate(dueDate, "yyyy-mm-dd ") : this.msg("label.none")) + '</span></div></td>';
                info += '<td width="45%"><div class=started"><label>' + this.msg("label.started") + ':</label><span>' + (startedDate ? Alfresco.util.formatDate(startedDate, "yyyy-mm-dd HH:MM"): this.msg("label.none")) + '</span></div></td></tr></table>';
                if (!workflow.isActive)
                {
                    var endedDate = workflow.endDate ? Alfresco.util.fromISO8601(workflow.endDate) : null;
                    info += '<div class=ended"><label>' + this.msg("label.ended") + ':</label><span>' + (endedDate ? Alfresco.util.formatDate(endedDate, "longDate") : this.msg("label.none")) + '</span></div>';
                }
                elCell.innerHTML = info;
            },

            /**
             * Actions custom datacell formatter
             *
             * @method renderCellActions
             * @param elCell {object}
             * @param oRecord {object}
             * @param oColumn {object}
             * @param oData {object|string}
             */
            renderCellActions:function MyWorkflows_onReady_renderCellActions(elCell, oRecord, oColumn, oData)
            {
                // Create actions using WorkflowAction
                this.createAction(elCell, this.msg("link.viewWorkflow"), "workflow-view-link", $siteURL('workflow-details?workflowId=' + oRecord.getData('id') + '&referrer=workflows&myWorkflowsLinkBack=true'));
                if (oRecord.getData('isActive'))
                {
                    this.createAction(elCell, this.msg("link.cancelWorkflow"), "workflow-cancel-link", function(event, oRecord)
                    {
                        this.cancelWorkflow(oRecord.getData("id"), oRecord.getData("message"));
                        Event.preventDefault(event);
                    }, oRecord);
                }
                else
                {
                    this.createAction(elCell, this.msg("link.deleteWorkflow"), "workflow-delete-link", function(event, oRecord)
                    {
                        this.deleteWorkflow(oRecord.getData("id"), oRecord.getData("message"));
                        Event.preventDefault(event);
                    }, oRecord);
                }
            }

        },true);
})();
